package com.enation.app.javashop.consumer.job.execute.impl;

import com.enation.app.javashop.consumer.job.execute.EveryDayExecute;
import com.enation.app.javashop.core.client.trade.BillClient;
import com.enation.app.javashop.core.orderbill.service.BillManager;
import com.enation.app.javashop.core.orderbill.utils.SettleUtils;
import com.enation.app.javashop.framework.util.DateUtil;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 商家结算单生成 状态修改
 */
@Component
public class SellerBillJob implements EveryDayExecute {

    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private BillClient billClient;
    @Autowired
    private BillManager billManager;

    /**
     * 每天执行
     */
    @Override
    public void everyDay() {
        try {
            this.logger.info("-----生成结算单执行-----");

            // 判断新结算功能是否上线了
            if(SettleUtils.isGoOnline(DateUtil.getDateline())){
                logger.info("由于新结算功能上线，不再定时生成结算单");
                return;
            }

            // 从系统中最新的结算单结束时间开始统计
            long lastBillEndTime = billManager.getLastBillEndTime();
            long endTime = DateUtil.endOfYesterday();
            if(lastBillEndTime < endTime){
                // 加1秒
                Date startDate = DateUtils.addSeconds(new Date(lastBillEndTime * 1000), 1);
                billClient.createBills(startDate.getTime() / 1000, endTime);
            }else{
                this.logger.error("结算单生成时间异常");
            }
        } catch (Exception e) {
            this.logger.error("每天生成结算单异常：", e);
        }
    }
}
